/*
 * Copyright 2018 - 2050 zyp.All Rights Reserved.
 *
 */
package com.zyp.common.message.common.resolver;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyp.common.message.common.domain.Result;

import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

public class WLJsonViewResolver extends MappingJackson2JsonView {

    private final org.slf4j.Logger log = LoggerFactory.getLogger(WLJsonViewResolver.class);

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);
        prepareResponse(request, response);
        renderMergedOutputModel(mergedModel, getRequestToExpose(request), response);
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        PrintWriter printWriter = response.getWriter();
        Object value = filterAndWrapModel(model, request);

        if (value != null && value instanceof Map) {
            
			Map map = (Map) value;
            for (Object obj : map.values()) {
                if (obj instanceof Result) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
                    String resultJson = objectMapper.writeValueAsString(obj);
                    printWriter.write(resultJson);
                    printWriter.flush();
                    return;
                }
            }
        } else {
            log.error("WLJsonViewResolver.renderMergedOutputModel error!");
        }
    }

}
